package de.slothsoft.commons.io;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public final class PollUtil {

	public static final void addListener(Path path, final IPollListener listener)
			throws IOException {
		addListener(path, listener, StandardWatchEventKinds.ENTRY_CREATE,
				StandardWatchEventKinds.ENTRY_MODIFY,
				StandardWatchEventKinds.ENTRY_DELETE);
	}

	public static final void addListener(Path path,
			final IPollListener listener, Kind<?>... events) throws IOException {
		final WatchService service = FileSystems.getDefault().newWatchService();
		final WatchKey watchKey = path.register(service, events);

		new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						WatchKey key = service.take();
						List<WatchEvent<?>> events = key.pollEvents();
						for (WatchEvent<?> event : events) {
							if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
								listener.performCreate();
							} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
								listener.performModify();
							} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
								listener.performDelete();
							}
						}
						watchKey.reset();
					} catch (InterruptedException e) {
						// TODO: handle this!
						break;
					}
				}
			};
		}.start();
	}

	private PollUtil() {
		// *hide*
	}
}
